import { defineStore } from "pinia";

import { list as getDict } from "@/api/dict";

import { getMenu, del } from "@/api/menu";
import { cloneDeep } from "lodash-es";
import { flattenDeepTree } from "@/utils/function";

const isCache = false; // 是否启用缓存

interface DictDataFace extends Record<string, DictFace[]> {}
interface CacheState extends Record<string, unknown> {
  dictList?: DictFace[];
  menuTreeList?: MenuBack[];
  menuLists: MenuBack[];
  dictData: DictDataFace;
}

export const useCacheStore = defineStore("cache", {
  state: (): CacheState => {
    return {
      dictList: undefined,
      menuTreeList: undefined,
      menuLists: [], // 平级的菜单列表，便于后面快速用id查询 type
      isMenuGet: false, // 是否正在请求获取菜单
      dictData: {},
    };
  },
  getters: {
    getToken(): undefined | string {
      return "";
    },
  },
  actions: {
    getDictist(): Promise<DictFace[]> {
      return new Promise((resolve, reject) => {
        if (this.dictList) {
          resolve(this.dictList);
        } else {
          this.updateDict().then((res) => {
            resolve(res);
          });
        }
      });
    },
    updateDict(): Promise<DictFace[]> {
      return new Promise((resolve, reject) => {
        getDict({
          current: 1,
          size: 1000,
        }).then((res) => {
          this.dictTreeList = res.data;
          resolve(this.dictTreeList);
        });
      });
    },
    /**
     * 获取菜单列表
     * @param isForce 是否强制一定要在当前回调中取得值
     * @returns 菜单列表或者空
     */
    getMenuTreeList(isForce: boolean = false): Promise<MenuBack[] | undefined> {
      return new Promise((resolve, reject) => {
        if (this.menuTreeList) {
          resolve(this.menuTreeList);
        } else {
          this.updateMenuTree(isForce).then((res) => {
            resolve(res);
          });
        }
      });
    },
    /**
     * 更新菜单列表
     * @param isForce 是否强制一定要在当前回调中取得值
     * @returns
     */
    updateMenuTree(isForce: boolean = false): Promise<MenuBack[] | undefined> {
      return new Promise((resolve, reject) => {
        if (this.isMenuGet && !isForce) {
          resolve(this.menuTreeList);
          return;
        }
        this.isMenuGet = true;
        getMenuTree()
          .then((res) => {
            this.menuTreeList = res.data; //  replaceIdSpace(res.data) as MenuBack[]
            this.menuLists =
              flattenDeepTree(cloneDeep(res.data), { ischildren: true }) || [];
            resolve(this.menuTreeList);
          })
          .finally(() => {
            this.isMenuGet = false;
          });
      });
    },
    /**
     * 获取数据字典
     * @param str 字典标识的字符或者数组
     * @returns 菜单列表或者空
     */
    getDictList(str: string | string[]): Promise<DictDataFace> {
      return new Promise(async (resolve, reject) => {
        // 归一化
        if (typeof str == "string") {
          str = [str];
        }
        let result: DictDataFace = {};
        console.log(this.dictTreeList);
        for (let i = 0; i < str.length; i++) {
          const data = this.dictTreeList?.find((v) => v.code === str[i]);

          if (data) {
            result[str[i]] = data.dictItemDtoList;
          }
        }
        console.log(result);
        resolve(result);
      });
    },
  },
});
